/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of LModeller.
 *
 * LModeller is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * LModeller is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LModeller.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.lmodeller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;


public class Logger {

	public static Logger INSTANCE;
	protected String userName;
	protected String directoryPath = "./logs/";
	protected BufferedWriter writer = null;
	
	public static Logger getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new Logger();
		}
		return INSTANCE;
	}	
	
	public void setDirectoryPath(String path)
	{
		this.directoryPath = path;
		if(!this.directoryPath.endsWith("/"))
		{
			this.directoryPath = this.directoryPath+"/";
		}
		File folder = new File(this.directoryPath);
		if(!folder.exists()) {
			try {
				folder.mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void setUserName(String name)
	{
		this.userName = name;
		if(userName == null || directoryPath == null ||
				userName.isEmpty() || directoryPath.isEmpty())
		{
			writer = null;
		}
		try {
			writer = new BufferedWriter(new FileWriter(directoryPath + userName + ".txt", true));
		} catch (IOException e) {
			writer = null;
			e.printStackTrace();
		}
	}
	
	public void log(String msg)
	{
		if (writer != null) {
			try {
				Calendar cal = Calendar.getInstance();
				//logger.write(cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND)+ ":" + cal.get(Calendar.MILLISECOND));
				writer.write(String.format("%1$te.%1$tm.%1$tY ", cal));
				writer.write(String.format("%1$tH:%1$tM:%1$tS:%1$tL", cal));
				writer.write(",");
				writer.write(msg + "\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(directoryPath == null || directoryPath.isEmpty())
		{
			System.err.println("LOGGER: directory not set (msg=\""+msg+"\")");
		}
		if(userName == null || userName.isEmpty())
		{
			System.err.println("LOGGER: userName not set (msg=\""+msg+"\")");
		}
	}
}
